package com.qf.java2107.yb.hotel.dao.impl;

import com.qf.java2107.yb.hotel.dao.FoodTypeDao;
import com.qf.java2107.yb.hotel.pojo.FoodType;
import com.qf.java2107.yb.hotel.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 菜系持久层实现
 * @author yb
 * @version 1.0
 * @date 2021-10-25
 **/
public class FoodTypeDaoImpl implements FoodTypeDao {

    private QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());

    @Override
    public List<FoodType> findAll() throws SQLException {

        String sql = "SELECT type_id typeId,type_name typeName FROM t_food_type";

        return queryRunner.query(JdbcUtils.getConnection(), sql, new BeanListHandler<>(FoodType.class));
    }

    @Override
    public List<FoodType> findLikeTypeName(String typeName) throws SQLException {

        String sql = "SELECT type_id typeId,type_name typeName FROM t_food_type WHERE type_name LIKE ?";

        return queryRunner.query(JdbcUtils.getConnection(), sql, new BeanListHandler<>(FoodType.class), typeName);
    }

    @Override
    public Integer findByTypeName(String typeName) throws SQLException {

        String sql = "SELECT type_id typeId FROM t_food_type WHERE type_name = ?";
        return queryRunner.query(JdbcUtils.getConnection(), sql, new ScalarHandler<>(), typeName);
    }

    @Override
    public void save(FoodType foodType) throws SQLException {

        String sql = "INSERT INTO t_food_type (type_name) VALUES (?)";
        queryRunner.update(JdbcUtils.getConnection(), sql, foodType.getTypeName());
    }

    @Override
    public void deleteById(int id) throws SQLException {

        String sql = "DELETE FROM t_food_type WHERE type_id = ?";
        queryRunner.update(JdbcUtils.getConnection(), sql, id);
    }

    @Override
    public FoodType findById(int id) throws SQLException {


        String sql = "SELECT type_id typeId,type_name typeName FROM t_food_type WHERE type_id = ?";

        return queryRunner.query(JdbcUtils.getConnection(), sql, new BeanHandler<>(FoodType.class), id);
    }

    @Override
    public void update(FoodType foodType) throws SQLException {

        String sql = "UPDATE t_food_type SET type_name = ? WHERE type_id = ?";

        queryRunner.update(JdbcUtils.getConnection(), sql, foodType.getTypeName(), foodType.getTypeId());

    }
}
